package com.qk.exception;

import com.qk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    //捕获所有异常
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("服务器异常:{}", e.getMessage());
        return Result.error("服务器异常");
    }

//捕获DuplicateKeyException 添加重复异常处理
    @ExceptionHandler
    public Result handleException(DuplicateKeyException e) {
        String message = e.getMessage();
        if (message.contains("Duplicate entry")){//思路就是 把需要展示给前台的信息 截取出来
            message = message.substring(message.indexOf("Duplicate entry"));
            //按空格切割返回关键字
            message = message.split(" ")[2];
            return Result.error(message+"已存在了.换一个吧!");
        }
        return Result.error( "服务器异常!!! ");
    }
    //登录 捕获异常
    @ExceptionHandler
    public Result handleException(BusinessException e) {
        log.error("业务异常!", e);
        return Result.error(e.getMessage());
    }
}
